package com.zrj.auth.core.userdetails.mobile;

import com.zrj.auth.pojo.dto.MemberAuthInfoDTO;
import com.zrj.auth.service.IUmsMemberService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author zhaorujie
 */
@Service("memberUserDetailsService")
@RequiredArgsConstructor
@Slf4j
public class MemberUserDetailsServiceImpl implements UserDetailsService {

    private final IUmsMemberService umsMemberService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return null;
    }

    public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
        MemberAuthInfoDTO member = umsMemberService.getByMobile(mobile);
        return getUser(member);
    }

    public UserDetails loadUserByOpenid(String openid) throws UsernameNotFoundException {
        MemberAuthInfoDTO member = umsMemberService.getByOpenid(openid);
        return getUser(member);
    }

    public UserDetails getUser(MemberAuthInfoDTO member) {
        MemberUserDetails userDetails = null;
        if (member != null) {
            userDetails = new MemberUserDetails(member);
        }
        if (userDetails == null) {
            throw new UsernameNotFoundException("该用户不存在");
        } else if (!userDetails.isEnabled()) {
            throw new DisabledException("该账号已被禁用");
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定");
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期");
        }
        return userDetails;
    }
}
